﻿namespace RevitStarter.Util
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Windows.Forms;
    using System.Xml;
    using System.Xml.Linq;
    using Autodesk.RevitAddIns;

    public static class AddinUtil
    {
        /// <summary>
        /// 根据Revit版本更新addin文件中dll的路径
        /// </summary>
        /// <param name="rvt">Revit版本</param>
        /// <param name="addInName">文件名称</param>
        /// <returns></returns>
        public static bool UpdateAddInFile(RevitProduct rvt, string addInName)
        {
            string destFile = AddinUtil.GetDesAddinPath(rvt, addInName);
            return UpdateAddInFile(rvt, destFile, addInName);
        }

        public static bool DeleteAddInFile(RevitProduct rvt, string addInName)
        {
            string destFile = AddinUtil.GetDesAddinPath(rvt, addInName);

            try
            {
                if (File.Exists(destFile))
                {
                    File.Delete(destFile); //删除目标文件
                }

                return true;
            }
            catch (Exception e)
            {
                string str = String.Format("删除addin文件{0}失败,请尝试手工删除,原因:{1}", destFile, e.Message);
                UiUtil.ErrorMessageBox2(str);
                return false;
            }
        }

        public static bool UpdateAddInFile(RevitProduct rvt, string desAddinPath, string addInName)
        {
            string strVer = rvt.Version.ToString(); //返回值Revit 2016
            string verNum = strVer.Replace("Revit", "").Trim(); //返回值2016
            
            string srcAddin = Path.Combine(Application.StartupPath); //修正为addin 源文件路径 Zcb 2021-10-10 09:43
 


            //原始的addin文件位置在具体版本下. 如: 2016/TestApp.addin
            string srcAddinPath = Path.Combine(srcAddin, addInName + ".addin").Trim();

            string dllDir = Path.Combine(Application.StartupPath, verNum);
            string dllPath = Path.Combine(dllDir, addInName + ".dll");

            if (!File.Exists(dllPath))
            {
                UiUtil.ErrorMessageBox("Dll文件不存在!\n" + dllPath);
                return false;
            }

            if (File.Exists(srcAddinPath))
            {
                XElement xElement;
                try
                {
                    xElement = XElement.Load(srcAddinPath);
                    foreach (XNode node in xElement.Nodes())
                    {
                        if (node.NodeType == XmlNodeType.Element)
                        {
                            XElement sub = node as XElement;

                            if (sub != null)
                            {
                                foreach (XNode item in sub.Nodes())
                                {
                                    XElement sub2 = item as XElement;
                                    if (sub2.Name == "Assembly")
                                    {
                                        sub2.Value = dllPath;
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {
                    UiUtil.ErrorMessageBox("解析addin文件失败!\n" + srcAddinPath);
                    return false;
                }

                try
                {
                    if (File.Exists(desAddinPath))
                    {
                        File.Delete(desAddinPath); //删除目标文件
                    }

                    xElement.Save(desAddinPath); //保存到目标文件
                }
                catch (Exception e)
                {
                    string msg = String.Format("更新addin文件{0}失败!\n原因:{1}", desAddinPath, e.Message);
                    UiUtil.ErrorMessageBox(msg);
                    throw;
                }


                return true;
            }
            else
            {
                UiUtil.ErrorMessageBox("原始addin文件不存在!");
                return false;
            }
        }

        /// <summary>
        /// 获得目标的addin全路径
        /// </summary>
        /// <param name="selItem"></param>
        /// <param name="addInName"></param>
        /// <returns></returns>
        public static string GetDesAddinPath(RevitProduct selItem, string addInName)
        {
            string destFile = Path.Combine(selItem.AllUsersAddInFolder, addInName + ".addin");
            return destFile;
        }

        /// <summary>
        /// 获得有效的Revit版本
        /// </summary>
        /// <param name="inputRevitVersions">输入参数</param>
        /// <returns></returns>
        public static List<RevitProduct> FilterValidRevitVersions(List<string> inputRevitVersions)
        {
            List<RevitProduct> allRevits = RevitProductUtility.GetAllInstalledRevitProducts();

            List<RevitProduct> revitList = allRevits.Where(d => inputRevitVersions.Contains(d.Version.ToString())).ToList();

            revitList = revitList.OrderBy(product => product.Version).ToList();
            
            return revitList;
        }
    }
}